# -*- coding: utf-8 -*-

from docx import Document
from docx.document import Document as Docu
from loguru import logger

from tools import safe


def write_table(doc: Docu, data: list, rows: int, cols: int, need_merge: list):
    """
       Args:
           doc: 文档对象
           data: 表格需要写入的数据
           rows: 表格行数
           cols: 表格列数
           need_merge: 需要合并的单元格，[[(行，列), (行，列)], [(行，列), (行，列)]...]

       Returns:

    """
    table = doc.add_table(rows=rows, cols=cols)
    table.style = 'Table Grid'
    for i in range(rows):
        for j in range(cols):
            plain = data[i * cols + j]
            if not plain:
                continue
            cell = table.cell(i, j)
            cell.text = plain

    for some in need_merge:
        table.cell(*some[0]).merge(table.cell(*some[1]))


@safe
def save_word(path: str, info: dict):
    doc: Docu = Document()
    doc.styles['Normal'].font.name = 'Microsoft YaHei'
    doc.add_paragraph('{}公司基本信息'.format(info['campany']))

    # 写入基本描述
    desc = [
        '公司名称', info['campany'], '公司法人', info['legalName'],
        '法人联系方式', info['legalPhone'], '', '',
        '员工信息', '', '', ''
    ]
    write_table(doc, desc, 3, 4, need_merge=[[(2, 0), (2, 3)]])

    # 写入员工信息
    for one in info['employeeInfor']:
        num = one.get('num') or ''
        data = [
            '员工{}'.format(num), '员工名', one['name'], '',
            '', '员工身份证', one['idcard'], '',
            '', '出生年月', one['birthday'], '',
        ]
        need_merge = [
            [(0, 2), (0, 3)],
            [(1, 2), (1, 3)],
            [(2, 2), (2, 3)],
            [(0, 0), (2, 0)]
        ]
        write_table(doc, data, 3, 4, need_merge=need_merge)

    # 保存文件
    doc.save(path)
    logger.success('写入成功  ==>  {}'.format(path))
    return True
